package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Region;
import cn.wolfcode.query.RegionQuery;
import cn.wolfcode.repository.RegionRepository;
import cn.wolfcode.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void insert(Region user) {
        repository.save(user);
    }

    @Override
    public void update(Region user) {
        repository.save(user);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> listAll() {
        return repository.findAll();
    }

    @Override
    public Page query(RegionQuery qo) {
        //创建查询对象
        Query query = new Query();
        //查询总条数
        long count = template.count(query, Region.class);
        if (count == 0){
            return Page.empty();
        }
        Pageable page = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(page);
        List<Region> list = template.find(query, Region.class);
        PageImpl<Region> regions = new PageImpl<>(list, page, count);
        return regions;
    }

    @Override
    public void changeIshot(String id, int hot) {
        Region region = this.get(id);
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public List<Region> queryIshot() {
        List<Region> regions = repository.findByIshotOrderBySequence(Region.STATE_HOT);
        return regions;
    }


}
